<template>
  <div>
    <div class="node" v-has="{action: 'order:count:statistics', effect: 'move'}">
    <div :class="[$style.search_box, $style.topSelect]">
        <div :class="$style.selectBox">
            <label>运营商:</label>
            <el-select
            v-model="api"
            clearable
            placeholder="请选择"
            >
            <el-option v-for="item in company" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
       </div>
       <div :class="$style.selectBox">
        <label>按运营商分组：</label>
        <el-select
          v-model="apiType"
          placeholder="请选择"
        >
          <el-option label="是" :value="true"></el-option>
          <el-option label="否" :value="false"></el-option>
        </el-select>
      </div>
       <div :class="$style.selectBox" >
        <label>创建时间：</label>
        <el-date-picker
          v-model="appointmentTime"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="timestamp"
          :picker-options="pickerOptions"
        ></el-date-picker>
      </div>
      <div :class="$style.selectBox">
        <label>按时间分组：</label>
        <el-select
          v-model="timeType"
          clearable
          placeholder="请选择"
        >
          <el-option label="年" value="year"></el-option>
          <el-option label="月" value="month"></el-option>
          <el-option label="日" value="date"></el-option>
        </el-select>
      </div>
      <div :class="$style.selectBox">
        <label>站点类型：</label>
        <el-select
          multiple
          collapse-tags
          width='150px'
          v-model="type"
          clearable
          placeholder="请选择"
        >
          <el-option label="自营" value="1"></el-option>
          <el-option label="第三方" value="2"></el-option>
          <el-option label="租用" value="3"></el-option>
          <el-option label="私有" value="9"></el-option>
        </el-select>
      </div>
       <div :class="$style.selectBox">
            <label>请选择:</label>
            <el-select v-model="siteId" clearable @change="changeSite('siteId')" placeholder="请选择站点">
              <el-option
                v-for="item in siteList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="pileId" clearable @change="changePile('pileId')" placeholder="请选择桩">
              <el-option
                v-for="item in pileList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="gunId" clearable @change="changeGun('gunId')" placeholder="请选择枪">
              <el-option
                v-for="item in gunList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
       </div>
        <div :class="$style.selectBox">
        <label>按站点设备分组：</label>
        <el-select
          v-model="tagType"
          clearable
          placeholder="请选择"
        >
          <el-option label="站点" value="site"></el-option>
          <el-option label="桩" value="pile"></el-option>
          <el-option label="枪" value="gun"></el-option>
        </el-select>
      </div>
      <div :class="$style.searchBox1" style="margin-left: 20px">
        <el-button  size="small" plain  icon="el-icon-search" @click="changeCheck">查询</el-button>        
      </div>
    </div>
    <Panel title="订单统计">
      <div slot="ext"><button  type="submit"  icon="el-icon-takeaway-box" :class="$style.export" @click="exportToExcel"><i class="el-icon-upload"></i>导出数据</button></div>
      <div slot="body">
        <TableEncapsulation
      
      :tableConfig="tableConfig"
      :tableData="tableData"
      :isSum="true"
    >
    <template slot="siteSlot" slot-scope="operation">
          <div>
            <template v-if="operation.data.siteName ">
              <div>{{operation.data.siteName}}</div>
              <div v-if=" operation.data.siteName!='采购电价合计'" :class="$style.gun">桩号：{{operation.data.pileSn}}</div>
              <div v-if=" operation.data.siteName!='采购电价合计'" :class="$style.gun">枪号：{{operation.data.gunSn}}</div>
            </template>
            <template v-else>
              <div>—</div>
            </template>
          </div>
        </template>
        <!-- <TablePager
          slot="pager"
          v-if="pager.use"
          :size="pager.size"
          :pageChange="pageChange"
          :show-total="pager.showTotal"
          :total="pager.total"
          :current="pager.current"
        >
          <span class="demonstration">GO></span>
        </TablePager> -->
    </TableEncapsulation>
    <div :class="$style.tab">直购电价表</div>
    <TableEncapsulation
      :border="true"
      :tableConfig="tableConfigZhi"
      :tableData="buyEle"
      :isSum="false"
    >
    </TableEncapsulation>
      </div>
   
    
    </Panel>
    </div>
    <div style="display: none;width:100%;height:100%;margin: auto;" v-has="{action: 'order:count:statistics', effect: 'noPremiss'}">
      <NoPremission></NoPremission>
    </div>
  </div>
</template>
<script>
import request from "@/tools/request";
import Panel from "@/components/Panel";
import TableEncapsulation from "@/components/TableEncapsulation";
import TablePager from "@/components/Pager";
import SearchInput from "@/components/SearchInput";
import { objectFilter } from "@/tools/array";
import { dateFormat } from "@/tools/time";

import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
export default {
  name: "orderStatistics",
  components: {
    TableEncapsulation,
    TablePager,
    Panel,
    SearchInput
  },
  data() {
    return {
      intro:'',
      type: ['1'],
      buyEle:[],
      tableData: [],
      company:[],
      timeType:'date',
      apiType:true,
      operation: true,
      tagType:"",
      pager: {
        use: true,
        total: 0,
        current: 1,
        size: 10,
        showTotal: true
      },
      api:'',
      gunId:'',
      siteId:"",
      siteList: [],
      pileId :"",
      pileList: [],
      gunList: [],
      phone: '',
      plate: '',
      siteName:"站点",
      wxSn: '',
      settlement: '',
      gu:1,
      feng: 1, 
      ping: 1, 
      jian: 1,

      appointmentTime: [new Date().getTime(), new Date().getTime()],
      props: {
          value: 'id',
          label: 'name',
          level:'pid',
          lazy: true,
         async lazyLoad (node, resolve) {
            const { level } = node;
            let url,datas
            if(node.level == 1){
               url = '/iot/pile/select'
               datas = {siteId:node.data.id}
            }else{
               url = '/iot/pile/gun/all'
               datas = {pile:node.data.id}
            }
            const nodes = await request({
                      url,
                      method: "POST",
                      data:datas
                    })
                    nodes.list.map( item => {
                      item.leaf = item.type >= 3
                      return item
                    })
                  if(nodes.code ==0)
                    resolve(nodes.list);
                  //  console.log('nodes------',nodes)
          }
        },
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      genare: [
        {
          label: "站点（桩/枪）",
          type: "slot",
          prop: "siteName",
          align: "center",
          slotName:"siteSlot",
          fixed: true
          },
        {
          label: "运营商",
          type: "other",
          prop: "apiName",
          align: "center",
          fnc: val => val ? val : '——',
          fixed: true
          },
          {
          label: "时间",
          type: "other",
          prop: "dateTime",
          align: "center",
          fnc: val => val ? val : '——',
          },
          {
          label: "实际到账金额",
          type: "text",
          prop: "amount",
          align: "center"
          },
          {
          label: "订单数量",
          type: "text",
          prop: "chargeNum",
          align: "center"
          },
          {
          label: "充电成功次数",
          type: "text",
          prop: "chargeSuccess",
          align: "center"
          },
          {
          label: "充电时长(小时)",
          type: "text",
          prop: "chargeTime",
          align: "center"
          },
          {
          label: "充电量",
          type: "text",
          prop: "electricity",
          align: "center",
          },
          {
          label: "电费",
          type: "text",
          prop: "powerPrice",
          align: "center"
          },
          {
          label: "服务费",
          type: "text",
          prop: "servicePrice",
          align: "center"
          },
          {
          label: "实收电费",
          type: "text",
          prop: "receivedPowerPrice",
          align: "center"
          },
          {
          label: "实收服务费",
          type: "text",
          prop: "receivedServicePrice",
          align: "center"
          },
          {
          label: "抵扣服务费",
          type: "text",
          prop: "comboServicePrice",
          align: "center"
          },
          {
          label: "附加费",
          type: "text",
          prop: "surcharge",
          align: "center"
          },
          {
          label: "谷-时段电量",
          type: "text",
          prop: "electricityGu",
          align: "center"
          },
          {
          label: "平-时段电量",
          type: "text",
          prop: "electricityPing",
          align: "center"
          },
          {
          label: "峰-时段电量",
          type: "text",
          prop: "electricityFen",
          align: "center"
          },
          {
          label: "尖-时段电量",
          type: "text",
          prop: "electricityJian",
          align: "center"
          },
      ]
    };
  },
  created() {
    
  },
  mounted(){
    this.getConfig()
    // this.getRate();
    this.companyTh()
    this.iotSite()
  },
  computed: {
    tableConfig () {
      return {
        selection: false,
        columnConfig: this.genare.filter(Boolean)
        }
    },
    tableConfigZhi () {
      return {
        selection: false,
        columnConfig: [
        {
          label: "月份",
          type: "text",
          prop: "name",
          align: "center",
          fixed: true
          },
          {
          label: "峰段",
          type: "text",
          prop: "price",
          align: "center"
          },
          {
          label: "电量(不包含私人桩)",
          type: "text",
          prop: "ele",
          align: "center"
          },
          {
          label: "直购总价",
          type: "text",
          prop: "amout",
          align: "center"
          },
          {
          label: "实收电费",
          type: "text",
          prop: "actul",
          align: "center"
          },
          {
          label: "差额",
          type: "text",
          prop: "division",
          align: "center"
          },
      ]
        }
    },
    groups () {
      let groups = []
      if(this.apiType){
        groups.push('api')
      }
      if(this.timeType == 'year'){
       groups.push('year') 
      }
      if(this.timeType == 'month'){
       groups.push('month') 
      }
      if(this.timeType == 'date'){
       groups.push('date') 
      }
      if(this.tagType){
        groups.push(this.tagType)
      }
         return  groups
    },
  },
  methods: {
    exportToExcel() {
      // 假设你有一个表格的数据
      const title = ["站点", "运营商", "时间","实际到账金额", "订单数量", "充电成功次数", "充电时长（小时）", "充电量", '电费', "服务费", "实收电费", "实收服务费", "抵扣服务费", "附加费", "谷段电量", "平段电量", "峰段电量", "尖段电量"]

      let tableData = this.tableData
      let newData = []
      tableData.map(item=>{
        var siteName = item.siteName ? item.siteName : '-'
        var apiName = item.apiName ? item.apiName : '-'
        var date = item.date ? item.date+'日' :  item.month ?  item.month+'月' :  item.year
        newData.push([siteName, apiName, date, item.amount, item.chargeNum, item.chargeSuccess, item.chargeTime, item.electricity, item.powerPrice, item.servicePrice, item.receivedPowerPrice, item.receivedServicePrice, item.comboServicePrice, item.surcharge, item.electricityGu, item.electricityPing, item.electricityFen, item.electricityJian])

      })
      const data = [title, ...newData]
      // console.log('data',data)
      // return
      // 创建工作簿
      const ws = XLSX.utils.aoa_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
 
      // 生成Excel文件
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
 
      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
      const today = new Date(); // 获取当前日期及时间
      const year = today.getFullYear(); // 获取年份
      const month = today.getMonth() + 1; // 获取月份（注意月份从0开始，所以要加1）
      const date = today.getDate(); // 获取日期
      
      // 输出今日日期（格式为YYYY-MM-DD）
      const todayDate = `${year}-${month}-${date}`;
      let name = todayDate+'订单统计导出.xlsx'
 
      // 下载文件
      saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), name);
    },
    async getRate() {
      let end = this.appointmentTime ? (dateFormat(this.appointmentTime[1], "yyyy-MM-dd")) : undefined
      let begin = this.appointmentTime ? (dateFormat(this.appointmentTime[0],"yyyy-MM-dd")) : undefined
      let typeList = this.type.length >0 ? this.type : ''
      let groups =  this.groups
      if(groups.length < 1){
        groups = ''
      }
      let api = this.api
      let siteId = this.siteId, gunId = this.gunId, pileId = this.pileId 
      let search = objectFilter({begin, end, groups, gunId, siteId, pileId, api ,typeList})
      const res = await request({
        url: "/order/count/statistics/day",
        method: "POST",
        data: search
      });
      let data = res.counts
      let fengEle = 0
      let pingEle = 0
      let guEle = 0
      let jianEle = 0
      let buyEle =[]
      let actul = 0
      let division =0
      data.map(item => {
        if(item.year){
          item.dateTime = item.year
        }
        if(item.month){
          item.dateTime = item.month
        }
        if(item.date){
          item.dateTime = item.date
        }
        if(item.chargeTime){
          item.chargeTime = (item.chargeTime /3600).toFixed(1)
        }
        if(item.comboServicePrice){
          item.receivedServicePrice = (item.receivedServicePrice - item.comboServicePrice).toFixed(2)
          // item.amount = (item.amount - item.comboServicePrice).toFixed(2)
        }
       if(item.apiName !='私人桩'){
        pingEle+=item.electricityPing
        guEle+=item.electricityGu
        fengEle+=item.electricityFen
        jianEle+=item.electricityJian
        actul+=item.receivedPowerPrice
       }
        return item
      })
      console.log('fengEle',guEle,pingEle,fengEle,jianEle)
      
      if(data.length>0){
        let jianPrice = (this.jian*jianEle).toFixed(2)
        let fengPrice = (this.feng*fengEle).toFixed(2)
        let pingPrice = (this.ping*pingEle).toFixed(2)
        let guPrice = (this.gu*guEle).toFixed(2)
        let all = (parseFloat(guEle)+parseFloat(pingEle)+parseFloat(fengEle)+parseFloat(jianEle)).toFixed(3)
        let allPrice = (parseFloat(guPrice)+parseFloat(pingPrice)+parseFloat(fengPrice)+parseFloat(jianPrice)).toFixed(2)
        division = (actul - allPrice).toFixed(2)
        buyEle[0]={name:'谷段', price: this.gu, ele: guEle.toFixed(3), amout: guPrice, actul: '-', division: '-'}
        buyEle[1]={name:'平段', price: this.ping, ele: pingEle.toFixed(3), amout: pingPrice, actul: '-', division: '-'}
        buyEle[2]={name:'峰段', price: this.feng, ele: fengEle.toFixed(3), amout: fengPrice, actul: '-', division: '-'}
        buyEle[3]={name:'尖段', price: this.jian, ele: jianEle.toFixed(3), amout: jianPrice, actul: '-', division: '-'}
        buyEle[4]={name:'合计', price:'-', ele: all, amout: allPrice, actul: (actul).toFixed(2), division: division}
      }

      if(this.timeType=='month'){

      }
      this.buyEle = buyEle
      this.tableData = data
    },

    
   
    pageChange(val) {
      this.pager.current = val;
      this.getRate();
    },
    async changeSite(){
      let url = '/iot/pile/select'
      let datas = {siteId:this.siteId}
      const res = await request({
                      url,
                      method: "POST",
                      data:datas
                    })
      this.pileList = res.list
      this.gunId = ''
      this.pileId = ''
      // this.getRate()
    },
    changeCheck(){
      this.getRate()
    },
    async changePile(){
      let url = '/iot/pile/gun/select'
      let datas = {pile:this.pileId}
      const res = await request({
                      url,
                      method: "POST",
                      data:datas
                    })
      this.gunList = res.list
      this.gunId = ''
      // this.getRate()
    },
    changeGun(){
      //  this.getRate()
    },
    changeSearch(key, val) {
      // this[key] = val;
      // if(this.api){
      //     this.apiGroups = 'api';
      // }
      // if(this.gunId){

      // }
    },
    changeSearchTag(key, val) {
      this[key] = val;
      if(this.api){
          this.groups = [this.api, this.timeType];
      }
      let arr = new Set(this.groups)
      arr.add()
      if(this.gunId){

      }
    },
     //站点
     async getConfig(){
      let res = await request({
      url: `/sys/config/info/23`,
      method: "GET",
      });
      console.log('res', res)
      if(res.config){
        let data = JSON.parse(res.config.val)
        this.feng = data.feng
        this.ping = data.ping
        this.gu = data.gu
        this.jian = data.jian
        // this.intro = `直购电价单价：谷（${data.gu}）,平（${data.ping}）,峰（${data.feng}）,尖（${data.jian}）`
      }else{
        // this.intro = '暂未配置直购电价'
      }
      this.getRate()
      //  this.siteList = list
    },
    //站点
    async iotSite(){
      let { list } = await request({
      url: "/iot/site/select",
      method: "POST",
      data: {}
      });
       this.siteList = list
    },
    //第三方公司
    async companyTh(){
      let { list } = await request({
      url: "/third/company/select",
      method: "POST",
      data: {}
      });
      let my = {id: 0, name: '自营'}
      this.company = [my, ...list]
    },
  }
}
</script>
<style lang='scss' module>
.tab{
  margin: 20px 10px;
    background: #c5c5c5;
    padding: 10px;
    width: 100px;
    border-top-right-radius: 20px;
    border-bottom-right-radius: 20px;
}
.intro{
  color: #979797;
    font-size: 14px;
}
.examine{
    display: flex;
    align-items: center;
    :global{
        div{
            color: #fff;
            padding: 10px;
            margin: 0 10px;
            border-radius: 2px;
            font-size: 14px;
            cursor: pointer;
            min-width: 60px;
            text-align: center;
        }
        .adopt{
                background: #409EFF;
        }
    }
}
.search_box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  :global {
    .el-input {
      width: 150px;
    }
    .el-select {
      .el-input {
        // width: 90px;
      }
    }
    .el-input__icon {
      line-height: 27px;
    }
    .el-range-separator{
      line-height: 26px;
    }
  }
}

.topSelect {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.gun{
  font-size: 11px;
}
.selectBox {
  margin: 4px 10px;
  :global {
    label {
      font-size: 14px;
      color: #666666;
    }
    .el-input__inner {
      height: 32px;
    }
    .el-input__suffix {
      line-height: 32px;
    }
    .el-date-editor--datetime{
    }
  }
}
.export {
  color: #FFF;
  background-color: #F56C6C;
  border-color: #F56C6C;
  border: 1px solid #F56C6C;
  border-radius: 1px;
  padding: 7px 10px;
}
.el-select .el-input .el-select__caret{
  color: #979797 !important;
}

</style>